package com.huixue.cn.ztej.weixin.util;

import javax.servlet.http.HttpServletRequest;

import com.huixue.cn.ztej.base.Constant;
import com.huixue.cn.ztej.weixin.bean.OAuthInfo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * @author Administrator
 *
 */
public class WeixinHelper {
	//https://api.weixin.qq.com/cgi-bin/user/info
	public static String getUserOpenId(String accessToken){  
        String result = null;  
        String requestUrl ="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken;  
        //requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);  
        JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null);  
        if(null != jsonObject){  
            result = jsonObject.get("data")+"";  
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
            if(jsonArray!=null && jsonArray.size()>0){
            	result = jsonArray.getString(0);
            }
            	
        }  
        return result;  
    } 
	
	
	public static OAuthInfo getUserOpenId(HttpServletRequest request){  
		String code = request.getParameter("code");
		OAuthInfo  aouAuthInfo = null;
		if(code!=null){
			 aouAuthInfo = WeixinUtil.getOAuthOpenId(Constant.AppID, Constant.AppSecret, code,request);
			 request.getSession().setAttribute("aouAuthInfo", aouAuthInfo);
		}else if(request.getSession().getAttribute("aouAuthInfo")!=null){
			aouAuthInfo = (OAuthInfo)(request.getSession().getAttribute("aouAuthInfo"));
		}else{
			aouAuthInfo = new OAuthInfo();
			aouAuthInfo.setOpenId("o4UWRwOwW8q7bOv5NYFJkAB7ayUY");
		}
		return aouAuthInfo;
		
	}
}
